#!/bin/bash
#
# 申请 Let's Encrypt SSL 证书
# 作者: 知汛项目组
# 最后更新: 2024-11-07

set -e

# 颜色定义
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

# 默认配置
DOMAIN=""
EMAIL=""
METHOD="http"
DRY_RUN=false

# 显示帮助
show_help() {
    cat << EOF
用法: $0 [选项]

自动申请 Let's Encrypt SSL 证书

必填选项:
    --domain DOMAIN    域名（如: ws.waterism.tech）
    --email EMAIL      邮箱地址

可选选项:
    --method METHOD    验证方式: http|dns（默认: http）
    --dry-run          测试模式，不实际申请
    --help             显示此帮助信息

示例:
    # HTTP-01 验证（推荐）
    sudo bash $0 --domain ws.waterism.tech --email admin@waterism.tech

    # DNS-01 验证（支持通配符）
    sudo bash $0 --domain ws.waterism.tech --email admin@waterism.tech --method dns

    # 测试模式
    sudo bash $0 --domain ws.waterism.tech --email admin@waterism.tech --dry-run
EOF
}

# 解析参数
while [[ $# -gt 0 ]]; do
    case $1 in
        --domain)
            DOMAIN="$2"
            shift 2
            ;;
        --email)
            EMAIL="$2"
            shift 2
            ;;
        --method)
            METHOD="$2"
            shift 2
            ;;
        --dry-run)
            DRY_RUN=true
            shift
            ;;
        --help)
            show_help
            exit 0
            ;;
        *)
            echo -e "${RED}未知参数: $1${NC}"
            show_help
            exit 1
            ;;
    esac
done

# 检查必填参数
if [ -z "$DOMAIN" ] || [ -z "$EMAIL" ]; then
    echo -e "${RED}错误: 缺少必填参数${NC}"
    show_help
    exit 1
fi

# 检查root权限
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}请使用root权限运行: sudo $0${NC}"
    exit 1
fi

echo "======================================"
echo "申请 Let's Encrypt SSL 证书"
echo "======================================"
echo "域名: $DOMAIN"
echo "邮箱: $EMAIL"
echo "验证方式: $METHOD"
[ "$DRY_RUN" = true ] && echo "模式: 测试模式"
echo ""

# 检查 certbot
if ! command -v certbot &> /dev/null; then
    echo -e "${YELLOW}[1/3] 安装 Certbot...${NC}"
    if [ -f /etc/debian_version ]; then
        apt update
        apt install -y certbot
    elif [ -f /etc/redhat-release ]; then
        yum install -y epel-release
        yum install -y certbot
    else
        echo -e "${RED}不支持的操作系统${NC}"
        exit 1
    fi
    echo -e "${GREEN}✓ Certbot 安装成功${NC}"
else
    echo -e "${GREEN}✓ Certbot 已安装${NC}"
fi

# 申请证书
echo -e "${YELLOW}[2/3] 申请证书...${NC}"

if [ "$METHOD" = "http" ]; then
    # HTTP-01 验证
    echo "使用 HTTP-01 验证"
    
    # 检查端口80
    if netstat -tlnp | grep -q ':80 '; then
        echo -e "${YELLOW}警告: 端口80已被占用，可能需要临时停止相关服务${NC}"
        echo "占用端口80的进程:"
        netstat -tlnp | grep ':80 '
        read -p "是否继续? (y/n) " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            exit 1
        fi
    fi
    
    if [ "$DRY_RUN" = true ]; then
        certbot certonly \
            --standalone \
            --preferred-challenges http \
            -d "$DOMAIN" \
            --email "$EMAIL" \
            --agree-tos \
            --no-eff-email \
            --dry-run
    else
        certbot certonly \
            --standalone \
            --preferred-challenges http \
            -d "$DOMAIN" \
            --email "$EMAIL" \
            --agree-tos \
            --no-eff-email
    fi
    
elif [ "$METHOD" = "dns" ]; then
    # DNS-01 验证
    echo "使用 DNS-01 验证"
    echo -e "${YELLOW}请按照提示添加 DNS TXT 记录${NC}"
    
    if [ "$DRY_RUN" = true ]; then
        certbot certonly \
            --manual \
            --preferred-challenges dns-01 \
            -d "$DOMAIN" \
            -d "*.$DOMAIN" \
            --email "$EMAIL" \
            --agree-tos \
            --no-eff-email \
            --dry-run
    else
        certbot certonly \
            --manual \
            --preferred-challenges dns-01 \
            -d "$DOMAIN" \
            -d "*.$DOMAIN" \
            --email "$EMAIL" \
            --agree-tos \
            --no-eff-email
    fi
else
    echo -e "${RED}不支持的验证方式: $METHOD${NC}"
    exit 1
fi

if [ $? -ne 0 ]; then
    echo -e "${RED}✗ 证书申请失败${NC}"
    exit 1
fi

if [ "$DRY_RUN" = true ]; then
    echo -e "${GREEN}✓ 测试成功${NC}"
    exit 0
fi

# 验证证书
echo -e "${YELLOW}[3/3] 验证证书...${NC}"

CERT_DIR="/etc/letsencrypt/live/$DOMAIN"

if [ ! -d "$CERT_DIR" ]; then
    echo -e "${RED}✗ 证书目录不存在: $CERT_DIR${NC}"
    exit 1
fi

echo "证书文件:"
ls -lh "$CERT_DIR/"

echo ""
echo "证书信息:"
openssl x509 -in "$CERT_DIR/fullchain.pem" -noout -subject -dates

echo ""
echo -e "${GREEN}✓ 证书申请成功${NC}"
echo ""
echo "证书位置: $CERT_DIR"
echo ""
echo "下一步:"
echo "1. 部署证书: sudo bash scripts/ssl-setup/deploy-certificates.sh --all"
echo "2. 配置自动续期: sudo bash scripts/ssl-setup/setup-auto-renew.sh"

